<template>
<!-- 患者信息 -->
  <el-form ref="form" label-width="100px">
    <div>
      <span style="color: #000000; font-size: 20px; font-weight: bold; ">患者信息</span>
      <hr style="border: none; border-top: 1px solid #cccccc;" />
      <el-form style="width: 100%; margin: 0 auto; padding: 20px; box-sizing: border-box;" label-width="100" >
        <el-row :gutter="80">
          <el-col :span="8">
            <div class="grid-content">
              <el-form-item >
                <template #label>
                  姓名<span class="required-star">*</span>
                </template>
                <el-input v-model="patientInformationForm.name" style="width: 200px"></el-input>
              </el-form-item>
              <el-row style="margin: 0;">
                <el-col :span="9">
                  <el-form-item>
                    <template #label>
                      年龄<span style="margin-right: 5px"> </span>
                    </template>
                    <label style="color: #3b82f6 ;"> {{ patientInformationForm.age }}</label>
                  </el-form-item>
                </el-col>
                <el-col :span="15">
                  <el-form-item label="血型" >
                    <el-input  @input="convertToUppercase" v-model="patientInformationForm.bloodType" style="width: 70px"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item>
                <template #label>
                  联系电话<span class="required-star">*</span>
                </template>
                <el-input v-model="patientInformationForm.phoneNum"  style="width: 200px"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content ">
              <el-form-item >
                <template #label>
                  性别<span class="required-star">*</span>
                </template>
                <el-radio-group v-model="patientInformationForm.gender"  style="margin-right: auto">
                  <el-radio-button label="男" value="1" />
                  <el-radio-button label="女" value="0" />
                </el-radio-group>
              </el-form-item>
              <el-form-item label="婚姻状况" >
                <el-radio-group v-model="patientInformationForm.maritalStatus" >
                  <el-radio-button label="未婚" value="未婚" />
                  <el-radio-button label="已婚" value="已婚" />
                </el-radio-group>
              </el-form-item>
              <el-form-item label="现住地址">
                <el-input v-model="patientInformationForm.address"  style="width: 320px"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content ">
              <el-form-item >
                <template #label>
                  证件号<span class="required-star">*</span>
                </template>
                <el-input  style="width: 250px" v-model="patientInformationForm.personId" :disabled="isPersonIdDisabled" @keydown.enter ="checkPatient" placeholder="输入身份证号后，按回车加载数据"></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <h3 style="margin-bottom: 10px;">补充信息</h3>
        <el-row :gutter="80">
          <el-col :span="8">
            <div class="grid-content" >
              <el-form-item label="紧急联系人" >
                <el-input v-model="patientInformationForm.emergencyContactName" style="width: 200px"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content">
              <el-form-item label="联系电话" >
                <el-input v-model="patientInformationForm.emergencyContactPhone" style="width: 320px"></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <h3 style="margin-bottom: 10px;">关联信息</h3>
        <el-row :gutter="80">
          <el-col :span="10">
            <div class="grid-content">
              <el-form-item label="医保卡号" >
                <el-input v-model="patientInformationForm.insuranceNum" style="width: 200px"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <!-- 按钮 -->
          <el-col :span="14">
            <div class="grid-content">
              <span style="color: #cccccc; font-size: 16px; font-weight: bold; margin-bottom: 0px ">请注意：若修改患者信息，请务必及时点击“保存”更新！</span>
              <el-button @click="resetPatientForm">重置</el-button>
              <el-button type="primary" @click="savePatientInformation">保存</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </el-form>

  <span style="color: #000000; font-size: 20px; font-weight: bold; ">就诊信息</span>
  <hr style="border: none; border-top: 1px solid #cccccc;" />
  <el-form style="width: 100%; margin: 0 auto; padding: 20px; box-sizing: border-box;" label-width="100" >
    <el-row :gutter="80">
      <el-col :span="8">
        <div class="grid-content">
          <el-form-item >
            <template #label>
              门诊类型<span class="required-star">*</span>
            </template>
            <el-select v-model="visitInfoTOBackend.baseType"  placeholder="请选择门诊类型" style="width: 200px">
              <el-option label="普通门诊" value="普通门诊"></el-option>
            </el-select>
          </el-form-item>
<!--   科室信息       -->
          <el-form-item >
            <template #label>
              科室<span class="required-star">*</span>
            </template>
            <el-select v-model="visitBaseInfo.department" placeholder="请选择科室" style="width: 200px" @change="getDoctor">
              <el-option v-for="item in visitBaseInfo.departments"
                         :label="item.departmentName" :value="item.departmentName"></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content ">
          <el-form-item >
            <template #label>
              费用类型<span class="required-star">*</span>
            </template>
            <el-select v-model="visitBaseInfo.feeType" placeholder="请选择费用类型" style="width: 200px" :disabled="isfeeType">
              <el-option label="自费" value="自费"></el-option>
              <el-option label="医保" value="医保"></el-option>
            </el-select>
          </el-form-item>
<!--      医生    -->
          <el-form-item >
            <template #label>
              医生<span class="required-star">*</span>
            </template>
            <el-select v-model="visitBaseInfo.doctorId" placeholder="请选择医生" style="width: 200px" @change="onDoctorChange">
<!--      响应式，医生名字和职级拼接        -->
              <el-option v-for="item in visitBaseInfo.doctors"
                         :label="getDoctorLabel(item)" :value="item.doctorId"></el-option>
            </el-select>

          </el-form-item>
          <el-form-item >
          </el-form-item>
        </div>
      </el-col>
          <el-col :span="8">
            <div class="grid-content ">
              <el-form-item >
                <template #label>
                  就诊类型<span class="required-star">*</span>
                </template>
                <el-select v-model="visitInfoTOBackend.type" placeholder="请选择就诊类型" style="width: 200px">
                  <el-option label="初诊" value="10"></el-option>
                  <el-option label="复诊" value="20"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
    </el-row>

<!--  挂号类型，费用  -->
    <el-row :gutter="80">
      <el-col :span="12">
        <div class="grid-content" >
          <div class="display: flex; align-items: center;" >
            <label style="margin-right: 5px; font-size: 16px; " >挂号种类:<label style="color: #3b82f6"> {{ visitInfoTOBackend.roleName }}</label></label>
            <label style="margin-left: 10px;font-size: 16px; ">挂号费用:<label style="color: #3b82f6"> ￥{{ visitInfoTOBackend.fee }}</label></label>
          </div>
        </div>
      </el-col>
      <!-- 按钮 -->
      <el-col :span="12">
        <div class="grid-content">
         <span style="color: #cccccc; font-size: 16px; font-weight: bold; margin-bottom: 0px ">请注意：重置会清空就诊信息！</span>
          <el-button @click="resetRegForm">重置</el-button>
<!--     点击确认挂号出现确认挂号弹窗     -->
          <el-button type="primary"  @click="confirmRegistration()">确认挂号</el-button>
        </div>
      </el-col>
    </el-row>
  </el-form>
<!-- 新建挂号弹窗 -->
  <el-dialog
      title="确认挂号"
      style="width: 1000px;padding:40px;font-weight: bold;"
      v-model="dialogVisible"
      :before-close="handleClose"
  >
    <div class="display: flex; align-items: center;" >
      <label style="margin-right: 5px; font-size: 16px; " >订单详情</label>
<!--   挂号详细信息   -->
      <div style="background-color: #F2F2F2; margin: 5px 0px;" >
        <el-row :gutter="20">
          <el-col :span="1">
          </el-col>
          <el-col :span="8">
            <div class="grid-content"  >
              <div class="info-container">
                <div><label style="margin-right: 5px; font-size: 16px; " >挂号人:<span style="margin-left: 1em; font-size: inherit;">{{employeeName}}</span></label></div>
                <div><label style="margin-right: 5px; font-size: 16px; " >挂号医生:<span style="margin-left: 1em; font-size: inherit;">{{ visitInfoTOBackend.doctorName }}</span></label></div>
                <div><label style="margin-right: 5px; font-size: 16px; " >挂号患者:<span style="margin-left: 1em; font-size: inherit;">{{ patientInformationForm.name }}</span></label></div>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content" >
              <div class="info-container">
                <div><label style="margin-right: 5px; font-size: 16px; " >挂号金额:<span style="margin-left: 1em; font-size: inherit;">￥{{ visitInfoTOBackend.fee }}</span></label></div>
                <div><label style="margin-right: 5px; font-size: 16px; " >挂号种类:<span style="margin-left: 1em; font-size: inherit;">{{ visitInfoTOBackend.roleName }}</span></label></div>
                <div><label style="margin-right: 5px; font-size: 16px; " >挂号类型:<span style="margin-left: 1em; font-size: inherit;">{{ visitInfoTOBackend.feeType }}</span></label></div>
              </div>
            </div>
          </el-col>
          <el-col :span="7">
            <div class="grid-content" >
              <div class="info-container">
                <div><label style="margin-right: 5px; font-size: 16px; " >挂号科室:<span style="margin-left: 1em; font-size: inherit;">{{ visitInfoTOBackend.department }}</span></label></div>
                <div><label style="margin-right: 5px; font-size: 16px; " >挂号时段:<span style="margin-left: 1em; font-size: inherit;">08:00-17:00</span></label></div>
                <div><label style="margin-right: 5px; font-size: 16px; " >挂号日期:<span style="margin-left: 1em; font-size: inherit;">{{ visitInfoTOBackend.visitDate }}</span></label></div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="display: flex; align-items: center;" >
      <label style="margin: 5px; font-size: 16px; " >支付方式</label><br/>
    </div>

    <el-form style="width: 100%; margin: 0 auto; padding: 10px; box-sizing: border-box;" label-width="100" >
      <el-row :gutter="80">
        <el-col :span="18">
<!--   当患者自费时，不能选择医保支付       -->
          <el-radio-group v-model="selectedPaymentMethod" @change="onPaymentMethodChange">
            <el-radio-button label="cash" :disabled="isSelfPay"  content="患者为自费状态，无法选择医保支付" >医保支付</el-radio-button>
            <el-radio-button label="qr-code">扫码支付</el-radio-button>
            <!-- 其他支付方式 -->
          </el-radio-group>

<!--          <div class="grid-content" v-if="isCashSelected">
            &lt;!&ndash;  确认收款金额    &ndash;&gt;
            <el-form-item label="应收金额">
              <label style="margin-right: 5px; font-size: 16px; " >￥{{visitInfoTOBackend.fee}}</label>
            </el-form-item>
            <el-form-item label="实收金额">
              &lt;!&ndash; 输入实付金额 &ndash;&gt;
              <span>￥</span><el-input v-model.number="paidAmount"  style="width: 100px"></el-input>
              &lt;!&ndash; 显示找零信息 &ndash;&gt;
              <p v-if="change >= 0">找零: {{ change }} 元</p>
              <p v-else-if="paidAmount > 0" style="color: red">支付金额不足，请增加支付金额。</p>
              <p v-else>请输入支付金额。</p>
            </el-form-item>
          </div>
        <div class="grid-content" v-if="isQrCodeSelected">

          </div>-->
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span style="color: #cccccc; font-size: 16px; font-weight: bold; margin-bottom: 0px ">点击“取消”按钮，即可返回挂号页面</span>
      <el-button @click="cancelRegistration()">取消</el-button>
      <el-button type="primary" @click="saveAttendance()">确认挂号</el-button>
    </template>
  </el-dialog>
<!--挂号成功弹窗-->
  <el-dialog
      title="挂号成功"
      style="width: 1000px;padding:40px;font-weight: bold;"
      v-model="successDialogVisible"
      :before-close="handleCloseSuccessRegForm"
  >
    <div class="success-container">
      <div class="success-message">
        挂号成功，小票已打印，请及时取走！<br>
        就诊单编号：<span class="amount">{{ attendanceId }}</span>
      </div>
    </div>
    <template #footer>
<!--   清空患者信息   -->
      <el-button type="primary" @click="handleCloseSuccessRegForm()">下一位</el-button>
<!--   继续使用该患者信息   -->
      <el-button type="primary" @click="continueReg()">继续挂号</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, onMounted, ref, watch} from "vue";
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";
// 定义正则表达式，用于验证身份证号,要求出生年月日在正常范围内
const personIdRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/;
// 定义正则表达式，用于验证手机号码
const phoneNumRegex = /^1[3-9]\d{9}$/;
//设置禁用状态：默认为false，表示可以输入  ，当成功查询或者保存患者信息后，设置为true，表示不能再输入
const isPersonIdDisabled = ref(false);
const isfeeType = ref(false);
//患者信息
const patientInformationForm = ref({
  id: null, // 患者ID，考虑到这是自增主键，这里设置为null
  name: '', // 姓名
  gender: '', // 性别, 女0 男1，这里可以是'0'或'1'
  personId: '', // 身份证号
  age: null, // 年龄
  bloodType: '', // 血型
  address: '', // 住址
  phoneNum: '', // 手机号码
  emergencyContactName: '', // 紧急联系人姓名
  emergencyContactPhone: '', // 紧急联系人联系方式
  maritalStatus: '', // 婚姻状况
  insuranceNum: '' // 医保号
});
// 为了保证血型格式一致，监听输入事件并将输入内容转换为大写
function convertToUppercase(value) {
  // 将输入的内容转换为大写
  const upperCaseValue = value.toUpperCase();
  // 更新数据模型中的值
  patientInformationForm.value.bloodType = upperCaseValue;
}
//查询患者信息表
const queryPatient = ref({
  id: null, // 注意：这里使用小写的 'id'，与 Java 的命名约定相匹配（如果需要）
  name: '',
  gender: '',
  phoneNum: '',
  personId: '',
  insuranceNum: ''
});
//更新查询患者信息表
function updateQueryPatient() {
  const { id, name, gender, phoneNum, personId, insuranceNum } = patientInformationForm.value;
  queryPatient.value = { id, name, gender, phoneNum, personId, insuranceNum };
}
//更新就诊信息：自费/医保
function updateFeeType() {
  //当患者信息存在医保号，则挂号类型为医保
  if (patientInformationForm.value.insuranceNum && patientInformationForm.value.insuranceNum.trim().length > 0){
    visitBaseInfo.value.feeType="医保";
    isfeeType.value = true;
    //医保时，可医保支付
    isSelfPay.value = false;
  }else {
    visitBaseInfo.value.feeType="自费";
    isfeeType.value = true;
    //自费时，不能选择医保支付
    isSelfPay.value = true;
  }
}

//查询是否存在该患者
const checkPatient = () => {
  //校验证件号合法，不能为空或格式错误
  if (!personIdRegex.test(patientInformationForm.value.personId)) {
    ElMessage.error('身份证号错误，请填写合法的身份证号')
    return;
  }
  // 更新查询患者信息表
  updateQueryPatient();
  console.log("查询是否存在该患者",queryPatient.value);
  let data= qs.stringify(queryPatient.value)
  axios.post(BASE_URL+'/v1/patient/registration/selectPatient',data).then(response =>{
    if(response.data.code===2001){
      if (response.data.data!==null){
        patientInformationForm.value = response.data.data;
        ElMessage.success('该患者信息已存在，可直接挂号！')
        isPersonIdDisabled.value = true;
        console.log("该患者信息已存在",patientInformationForm.value)
        updateFeeType();
      }
      else{
        console.log("该患者不存在");
        ElMessage.error('不存在该患者，请补充信息')
      }
    }else{
      ElMessage.error('查询错误，请联系管理员')
    }
  });
};
//保存患者信息
const savePatientInformation = () => {
  // 校验姓名不为空
  if (!patientInformationForm.value.name.trim()) {
    ElMessage.error('姓名不能为空!');
    return;
  }
  // 校验性别不为空且为'0'或'1'
  if (!['0', '1'].includes(patientInformationForm.value.gender)) {
    ElMessage.error('请选择性别!');
    return;
  }
  //校验证件号合法，不能为空或格式错误
  if (!personIdRegex.test(patientInformationForm.value.personId)) {
    ElMessage.error('身份证号错误，请填写合法的身份证号！')
    return;
  }
  // 校验患者联系电话格式合法
  const phoneNum = patientInformationForm.value.phoneNum.trim();
  if (phoneNum && !phoneNumRegex.test(phoneNum)) {
    ElMessage.error('患者联系电话错误，请填写合法的手机号码！');
    return ; // 直接返回，避免继续执行其他校验
  }
  //如果有紧急联系人姓名，则联系电话不能为空
  if (patientInformationForm.value.emergencyContactName && !patientInformationForm.value.emergencyContactPhone) {
    ElMessage.error('紧急联系人联系电话不能为空！');
    return ; // 直接返回，避免继续执行其他校验
  }
  //校验紧急联系人联系电话格式合法
  const emergencyContactPhoneNum = patientInformationForm.value.emergencyContactPhone.trim();
  if (emergencyContactPhoneNum && !phoneNumRegex.test(emergencyContactPhoneNum)) {
    ElMessage.error('紧急联系人联系电话错误，请填写合法的手机号码!')
    return ; // 直接返回，避免继续执行其他校验
  }

  console.log("保存患者信息",patientInformationForm.value);
  let data= qs.stringify(patientInformationForm.value)
  axios.post(BASE_URL+'/v1/patient/registration/savePatient',data).then(response =>{
    if(response.data.code===2001){
      if (response.data.data==1){
        ElMessage.success('保存患者信息成功！');
        //需要再查询患者id
        checkPatient();
      }else {
        ElMessage.error('保存患者信息失败！');
      }
    }else{
      ElMessage.error('保存患者信息失败！');
    }
  });

};
//清空患者信息
const resetPatientForm = () => {
  isPersonIdDisabled.value = false;
  patientInformationForm.value = {
    id: null,
    name: '',
    gender: '',
    personId: '',
    age: '',
    bloodType: '',
    address: '',
    phoneNum: '',
    emergencyContactName: '',
    emergencyContactPhone: '',
    maritalStatus: '',
    insuranceNum: ''
  };
  queryPatient.value = {
    id: null,
    name: '',
    gender: '',
    personId: '',
    age: '',
    bloodType: '',
    address: '',
    phoneNum: '',
    emergencyContactName: '',
    emergencyContactPhone: '',
    maritalStatus: '',
    insuranceNum: ''
  };
  //清空就诊信息中与患者信息相关的费用类型
  visitBaseInfo.value.feeType='';
  // 重置就诊信息
  resetRegForm();
  // 清空实收金额（计算器）
  paidAmount.value = 0;
};
//清空就诊信息
const resetRegForm = () => {
  //清空前端的就诊信息，保留门诊科室列表
  visitBaseInfo.value = {
    ...visitBaseInfo.value,
    department:'',//门诊科室
    doctors:[],//门诊医生列表
    doctorName:'',//门诊医生
    doctorId: null,//医生id
    roleName:'',//医生职级

  }
  //清空传给后端的挂号信息
  visitInfoTOBackend.value = {
    baseType: '',
    feeType: '',
    type: '',
    patientId: null,
    doctorId: null,
    doctorName:'',
    roleName:'',
    fee: null,
    realFee: null,
    visitDate: null,
    department:'',
  };
  //清空实收金额（计算器）
  paidAmount.value = 0;
}

/*就诊信息收集*/
//门诊信息，从后端获取
const visitBaseInfo = ref({
  departments:[],//门诊科室列表
  department:'',//门诊科室
  doctors:[],//门诊医生列表
  doctorName:'',//门诊医生
  doctorId: null,//医生id
  roleName:'',//医生职级
  feeType: ''
})
// 方法：生成医生选项的标签文本
function getDoctorLabel(doctor) {
  return `${doctor.doctorName} - ${doctor.roleName}`;
}
//挂号信息，传给后端
const visitInfoTOBackend = ref({
  //普通门诊
  baseType: '',
  //费用类型，自费
  feeType: '',
  // 门诊类型，对应 attendance_record 表中的 type 字段
  type: '', // 初诊"10"；复诊"20"
  patientId: null, // 患者ID
  doctorId: null, // 医生ID
  doctorName:'',//医生姓名
  roleName:'',//医生职级
  fee: null, // 挂号费
  visitDate: null, // 挂号日期
  department:'',//门诊科室
  insuranceNum: '' // 医保号
});
// 定义计算费用的方法
const calculateFee = () => {
  if (visitInfoTOBackend.value.roleName === '主任医师') {
    if (visitBaseInfo.value.feeType==='医保') {
      visitInfoTOBackend.value.fee = 60 * 0.8;
    } else {
      visitInfoTOBackend.value.fee = 60;
    }
  } else if (visitInfoTOBackend.value.roleName === '普通医师') {
    if (visitBaseInfo.value.feeType==='医保') {
      visitInfoTOBackend.value.fee = 50 * 0.8;
    } else {
      visitInfoTOBackend.value.fee = 50;
    }
  }
};
// 使用 watch 监听 roleName 和 feeType 的变化
watch([() => visitInfoTOBackend.value.roleName, () => visitBaseInfo.value.feeType],
    ([newRoleName, newFeeType], [oldRoleName, oldFeeType]) => {
      calculateFee(); // 当任意一个被监听的属性变化时，重新计算费用
    },
    { immediate: true } // 立即执行一次以初始化费用
);
//从后端获取科室列表
const getDepartment = () => {
  axios.get(BASE_URL+'/v1/patient/registration/selectDepartment').then(response =>{
    if(response.data.code===2001){
      if (response.data.data!==null){
        console.log("有科室");
        visitBaseInfo.value.departments = response.data.data;
        console.log("科室列表",visitBaseInfo.value.departments);
      }
      else{
        console.log("科室为空");
        ElMessage.error('科室为空，请联系管理员补充科室信息！')
      }
    }else{
      ElMessage.error('获取科室错误，请联系管理员！')
    }
  });
};
//获取医生列表
const getDoctor = () => {
  //传递科室信息
  let data= qs.stringify({
    department: visitBaseInfo.value.department
  })
  //清空医生列表
  visitBaseInfo.value.doctors=[];
  visitBaseInfo.value.doctorId= null;
  axios.get(BASE_URL+'/v1/patient/registration/selectDoctor?'+data).then(response =>{
    if(response.data.code===2001){
      if (response.data.data!==null){
        console.log("有医生");
        visitBaseInfo.value.doctors = response.data.data;
        console.log("医生列表",visitBaseInfo.value.doctors);
      }
      else{
        console.log("医生为空");
        ElMessage.error('医生为空，请联系管理员补充医生信息！')
      }
    }else {
      ElMessage.error('获取医生错误，请联系管理员！')
    }
  });
};
//选择医生后，获取当前挂号的所有信息
const onDoctorChange = () => {
  console.log("选择医生后，获取当前挂号的所有信息");
  const selectedDoctor = visitBaseInfo.value.doctors.find(doctor => doctor.doctorId === parseInt(visitBaseInfo.value.doctorId));
  if (selectedDoctor) {
    console.log('所选医生的全部信息:', selectedDoctor);
    visitInfoTOBackend.value.doctorId = selectedDoctor.doctorId;
    visitInfoTOBackend.value.doctorName = selectedDoctor.doctorName;
    visitInfoTOBackend.value.roleName = selectedDoctor.roleName;
    visitInfoTOBackend.value.department = selectedDoctor.department;
    // 调用 calculateFee() 方法来获取挂号费
    calculateFee();
    console.log("挂号信息",visitInfoTOBackend.value);
  } else {
    console.error('未找到对应的医生信息');
  }
};
//挂号业务，第一次点击确认挂号后 校验数据
const confirmRegistration = () => {
  //校验数据
  if (!patientInformationForm.value.id) {
    ElMessage.error('患者信息不能为空!');
    return;
  }
  if (!visitInfoTOBackend.value.baseType.trim()) {
    ElMessage.error('请选择门诊类型!');
    return;
  }
  if (!visitInfoTOBackend.value.type.trim()) {
    ElMessage.error('请选择就诊类型!');
    return;
  }
  if (!visitBaseInfo.value.department.trim()) {
    ElMessage.error('请选择门诊科室!');
    return;
  }
  if (!visitInfoTOBackend.value.doctorId) {
    ElMessage.error('请选择医生!');
    return;
  }
  visitInfoTOBackend.value.feeType = visitBaseInfo.value.feeType;
  //获取当前日期
  visitInfoTOBackend.value.visitDate = formattedDate();
  //获取当前患者
  visitInfoTOBackend.value.patientId = patientInformationForm.value.id;
  dialogVisible.value = true;

};
//就诊单号
const attendanceId = ref(null);
//关闭挂号确认页面
const cancelRegistration = () => {
  dialogVisible.value = false;
};

/*支付选项 已弃用现金*/
const selectedPaymentMethod = ref('cash');
// 假设初始状态不是自费
const isSelfPay = ref(false);
// 根据实际逻辑更新isSelfPay的值



// 判断是否选择了“现金”
const isCashSelected = computed(() => selectedPaymentMethod.value === 'cash');

// 判断是否选择了“扫码支付”
const isQrCodeSelected = computed(() => selectedPaymentMethod.value === 'qr-code');
// 监听支付方式的变化以生成二维码
watch(selectedPaymentMethod, (newVal) => {
  if(newVal === 'qr-code') {
    generateQRCode();
  }
});
// 生成二维码
function generateQRCode() {
  console.log('生成二维码')
}

// 支付方式改变时触发
function onPaymentMethodChange(value) {
  selectedPaymentMethod.value = value;
}
//计算找零
// 实际支付的金额
const paidAmount = ref(0);

// 计算找零
const change = computed(() => {
  return paidAmount.value - visitInfoTOBackend.value.fee;
});

// 监听支付金额的变化
watch(paidAmount, (newValue) => {
  if (newValue < visitInfoTOBackend.value.fee) {
    console.log('支付金额不足');
  } else {
    console.log(`找零金额为: ${change.value} 元`);
  }
});
//挂号-传给后端
const saveAttendance = () => {
  //实收金额不能为空
  /*if (!paidAmount.value) {
    ElMessage.error('实收金额不能为空!');
    return;
  }
  //实收金额不能小于挂号费
  if (paidAmount.value < visitInfoTOBackend.value.fee) {
    ElMessage.error('实收金额不能小于挂号费!');
    return;
  }*/
  console.log("保存挂号信息",visitInfoTOBackend.value);
  let data = qs.stringify(visitInfoTOBackend.value)
  axios.post(BASE_URL+'/v1/attendance/insert',data).then(response =>{
    if (response.data.code===2001){
      if (response.data.data!=null){
        ElMessage.success('挂号成功！');
        attendanceId.value = response.data.data;
        console.log("挂号订单号信息", attendanceId.value);
        successDialogVisible.value = true;
        dialogVisible.value = false;
      }else {
        ElMessage.error('挂号失败，请重试');
      }
    }else {
      ElMessage.error('挂号失败,请联系管理员');
    }
  });
};
//获取当前日期
const formattedDate= ()=>{
  const today = new Date();
  // 获取年、月、日
  const year = today.getFullYear();
  // JavaScript中的月份是从0开始的，所以需要加1，同时检查是否需要补0
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  // 返回格式化的日期字符串
  return `${year}-${month}-${day}`;
}
onMounted(()=>{
  getDepartment();//一进入页面就需要加载科室列表
  formattedDate();//一进入页面就需要加载当前日期
})
/*关于弹窗*/
// 定义方法，避免误触导致关闭弹窗
const handleClose = () => {
  if(confirm('关闭后挂号信息清空，请谨慎操作！')){
    //用户确认关闭后,关闭弹窗
    dialogVisible.value = false;
    //清空已输入的表单数据
    resetPatientForm();
  }
};
//定义变量控制弹窗是否出现
//挂号确认弹窗
const dialogVisible = ref(false);
//成功挂号弹窗
const successDialogVisible = ref(false);
//挂号成功后关闭，新患者挂号
const handleCloseSuccessRegForm = () => {
  //清空患者和就诊信息
  resetPatientForm();
  //关闭弹窗
  successDialogVisible.value = false;
};
//挂号成功后继续挂号，同一个患者挂号
const continueReg = () => {
  //关闭弹窗
  successDialogVisible.value = false;
  //只清空就诊信息，保留患者信息
  resetRegForm();
};

//定义变量用于保存操作人id
const employeeName = getUserInfo().name
//获取当前登录用户的全局方法
window.getUserInfo = ()=>{
  return localStorage.userInfo ? JSON.parse(localStorage.userInfo) : null;
}
</script>

<style scoped>

.required-star {
  color: red;
  margin-left: 2px; /* 调整星号与文字之间的间距 */
}

.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.info-container {
  font-size: 16px;
  line-height: 1.5; /* 控制行间距 */
}

.info-container div {
  margin-bottom: 10px; /* 控制每行之间的间距 */
}
.success-container {
  padding: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px; /* 设置容器的高度 */
}

.success-message {
  text-align: center;
}

</style>